<template>
  <div class="wrapper addbox">
    <div class="bg-login" v-show="bgLogin"></div>
    <el-form label-position="right" class="demo-form-inline" :model="addCustomerForm" :rules="rules" ref="addCustomerForm"
             label-width="100px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="客户名称:" prop="customerName">
            <el-input class="form-input" style="width: 180px" v-model="addCustomerForm.customerName" placeholder="客户名称" size="small" @keyup.enter.native="matchCustomers"></el-input>
            <el-button type="primary" @click="matchCustomers"  size="small"><i class="fa fa-search"></i> 匹配</el-button>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="手机号码:">
            <el-input class="form-input" style="width: 180px" v-model="addCustomerForm.tel" placeholder="手机号码" size="small" :disabled="onlyRead"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="客户类别:" >
            <el-select v-model="addCustomerForm.customerLevel"  style="width: 180px" placeholder="请选择" size="small" :disabled="onlyRead">
              <el-option v-for="item in customerLevels" :label="item.value"
                         :value="item.key.toString()" :key="item.key"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="QQ:">
            <el-input class="form-input" style="width: 180px" v-model="addCustomerForm.qq" placeholder="QQ" size="small" :disabled="onlyRead"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="联系人名称:">
            <el-input class="form-input" style="width: 180px" v-model="addCustomerForm.contactName" placeholder="联系人名称" size="small" :disabled="onlyRead"></el-input>
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="销售员:">
            <el-input class="form-input" style="width: 180px" v-model="userName" :disabled="true" size="small"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="客户来源:">
            <el-input class="form-input" style="width: 180px" v-model="addCustomerForm.customerFrom" placeholder="客户来源" size="small" :disabled="onlyRead"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item style="width: 280px" label="所属行业:">
            <industry-select :disabled = "onlyRead" :value="industryValue"/>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="是否标记:">
            <el-radio v-model="radio" class="radio" label="1" :disabled="onlyRead">是</el-radio>
            <el-radio v-model="radio" class="radio" label="0" :disabled="onlyRead">否</el-radio>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item style="width: 280px" label="客户地址:">
            <area-select :disabled = "onlyRead" :value="addrValue"/>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="办公电话:">
            <el-input class="form-input" style="width: 180px" v-model="addCustomerForm.phone" placeholder="格式：0557-0123456" size="small" :disabled="onlyRead"></el-input>
          </el-form-item>
        </el-col>
       
        <el-col :span="8">
          <el-form-item label="KP:">
            <el-checkbox v-model="Flag" :disabled="onlyRead"></el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="详细地址:">
            <el-input v-model="addCustomerForm.address"  style="width: 180px" placeholder="详细地址" size="small" :disabled="onlyRead"></el-input>
          </el-form-item>
        </el-col>

         <el-col :span="8">
          <el-form-item label="客户网站:">
            <el-input v-model="addCustomerForm.customerWeb"  style="width: 180px" placeholder="请输入以http://开头的网址" size="small" :disabled="onlyRead"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-table :data="customerList" v-model="customerList" style="width: 100%;margin-top:20px;">
      <el-table-column label="客户名称" min-width='95' className="cloumlist">
        <template scope="scope" >
          <span v-show="scope.row.publicFlag == 0 ? true : false" >{{ scope.row.customerName }}</span>
          <span v-show="scope.row.publicFlag == 1 ? true : false" class="seas" @click="goSeasDetail(scope.row)">{{ scope.row.customerName }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="customerTypeName" label="客户类别" min-width='111'></el-table-column>

      <el-table-column label="销售员" min-width='80'>
        <template scope="scope" >
          <span v-show="scope.row.publicFlag == 0 ? true : false" >{{ scope.row.name }}</span>
          <span v-show="scope.row.publicFlag == 1 ? true : false" class="seas" @click="goSeas(scope.row.customerName)">{{  "公海客户" }}</span>
          
        </template>
      </el-table-column>

      <el-table-column prop="contactName" label="联系人名称" min-width='124'></el-table-column>
      <el-table-column prop="tel" label="手机号码" min-width='94'></el-table-column>
      <el-table-column prop="customerFrom" label="客户来源" min-width='94'></el-table-column>
      <el-table-column prop="lastFollowTime" label="最新跟进时间" min-width='120'></el-table-column>
      <el-table-column prop="planTime" label="下次联系时间" min-width='150'></el-table-column>
    </el-table>

    <el-pagination
            
            style="margin-top: 40px"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            :current-page="pagingData.pageNum"
            :page-sizes="pagingData.pageSizes"
            :page-size="50"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagingData.total">
    </el-pagination>

    <el-row class="action_row" >
      <el-col :span="12">
        <el-button :disabled="onlyRead" class="top_save" type="primary" @click="onSubmit" size="small"><i class="fa fa-save"></i> 保存</el-button>
      </el-col>
      <el-col :span="12">
        <el-button class="top_close" type="danger" @click="close"  size="small"><i class="fa fa-sign-out"></i> 退出</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import Vue from 'vue'
  import axios from '~/plugins/axios';
  import * as types from '../../store/mutation-types/customer/index';
  import {BG_LOGIN,USER_DATA} from '../../store/mutation-types/user_login/index';
  import {setToken, getCookie,validTel,validFixedTel ,checkQQ, checkeurl} from '../../utils/auth'
  import {mapGetters, mapActions, mapMutations} from 'vuex';
  import {
    Row, Col, Form, FormItem, Input, Select, Option, Radio, DatePicker, Cascader,
    Button, Table, TableColumn, Checkbox, Message, Pagination
  } from 'element-ui'
  import AreaSelect from '~components/areaSelect.vue'
  import IndustrySelect from '~components/industrySelect.vue'

  Vue.use(Row);
  Vue.use(Col);
  Vue.use(Form);
  Vue.use(FormItem);
  Vue.use(Input);
  Vue.use(Select);
  Vue.use(Option);
  Vue.use(Radio);
  Vue.use(DatePicker);
  Vue.use(Cascader);
  Vue.use(Button);
  Vue.use(Table);
  Vue.use(TableColumn);
  Vue.use(Checkbox);
  Vue.use(Pagination);

  export default {
    components: {
        AreaSelect,
        IndustrySelect
    },
    head(){
        return {
            title: "添加客户",
            meta: [
                { hid: 'add-customer', name: 'add-customer', content: 'add-customer' }
            ]
        }
    },
    computed: {
      ...mapGetters({
          customerLevels: 'getSalesCategoryList',
          bgLogin: 'getBgLogin',
          pageTabsList: 'getPageTabsList',
          addCustomerForm: 'addCustomerForm'
      }),

    },
    data () {
      return {
          tabName: '添加客户',
        onlyRead: true,
        rules: {
          customerName: [
            {required: true, message: '请输入客户名称', trigger: 'blur'}
          ]
        },
        addrValue:[],
        industryValue:[],
        detail: {
          customerName: '',         //用户名
          customerLevel: '',         //客户类别
          contactName: '',          //联系人
          tel: '',                 //手机号
          customerFrom: '',        //客户来源
          customerIndustry: '',     //所属行业
          kpFlag: '',              //KP标记，0不是关键人，1关键人
          address: '',            //公司详细地址
          userId: '',                  //销售员id
          customerWeb: '',          //	客户网站
          provinceId: '',
          cityId: '',
          areaId: '',
          phone: '',         //电话号码
          qq: '',
          signFlag: ''              //是否标记
        },
        radio: '0',
        Flag: false,
        userName: '',
        filter: {
          customerName: '',
          pageSize: 50, // 每页条数
          pageNum: 1,
          publicFlag : -1
        },
        pagingData: {
            pageSizes: [10, 20, 50],  // 每页可选条数列表,
            total: 0,
            pageNum: 1
        },
        customerList: []
      };
    },
    methods: {
      //搜索条件加入store
      setFilterCookie(){
          let data = JSON.stringify(this.addCustomerForm.customerName);
          this.$store.commit('ADD_CUSTOMER_FILTER',{data});
          //setToken('addCustomerFilter',data);
      },
      // 客户类别
      getCustomerLevels (params) {
        this.$store.dispatch('salesCategoryList', params);
      },
      onSubmit() {
        if (!this.filter.customerName) {
          Message.warning({
            message: '请输入客户名称'
          });
          return;
        }else if(this.addCustomerForm.tel && validTel(this.addCustomerForm.tel) == false) {
            Message.warning({
                message: '手机号码格式不正确'
            });
            return;
        }else if(this.addCustomerForm.phone && validFixedTel(this.addCustomerForm.phone) == false) {
            Message.warning({
                message: '办公电话格式不正确'
            });
            return;
        }else if(this.addCustomerForm.qq && checkQQ(this.addCustomerForm.qq) == false) {
            Message.warning({
                message: 'QQ号格式不正确'
            });
            return;
        }
        if (this.Flag) {
          this.addCustomerForm.kpFlag = '1';
        } else {
          this.addCustomerForm.kpFlag = '0';
        }
        this.addCustomerForm.signFlag = this.radio;     //是否标记
        this.addCustomerForm.customerName = this.filter.customerName;

//      if(this.addCustomerForm.phone){
//          var phone = this.addCustomerForm.phone.split('-');
//          this.addCustomerForm.phone = phone.join('');
//      }

        this.$store.dispatch('customerAdd', this.addCustomerForm)
          .then((response) => {
            if(!response){return}
            let result = response.data;
            if (result.successed && result.successed == true) {
              Message.success({
                message: '操作成功'
              });
              this.$router.replace('/customer')
            } else {
              Message.warning({
                message: result.message
              });
            }
          })
          .catch((error) => {
            Message.error({
              message: result.message
            });
          });
      },
      close() {
        window.history.go(-1);
      },
      getCityId(id){
        this.addCustomerForm.provinceId = id[0];
        this.addCustomerForm.cityId = id[1];
        this.addCustomerForm.areaId = id[2];
      },
      matchCustomers() {
        this.filter.customerName =  this.addCustomerForm.customerName;
        this.filter.mathchFlag = 1;
        if (!this.filter.customerName) {
          Message.warning({
            message: '请输入客户名称'
          });
          return;
        }
        this.setFilterCookie();
        this.$store.dispatch('customerList', this.filter)
          .then((response) => {
            if(!response){
              return
            }
            let result = response.data;
            if (result.successed = true) {
              this.customerList = result.data.list;
                    let name = this.addCustomerForm.customerName;
                    this.$store.commit('INIT_ADD_CUSTOMER_FORM',{data:name});
                    if(this.customerList.length > 0) {
                      //初始化form 
                      this.onlyRead = true;
                    }else if(this.customerList.length == 0){
                      this.onlyRead = false;
                    }
                for(var i=0;i < this.customerList.length;i++) {
                      if(name === this.customerList[i].customerName){
                        this.onlyRead = true;
                        return;
                      }
                      if( name != this.customerList[i].customerName){
                      this.onlyRead = false;
                      }
                      if(this.customerList[i].publicFlag == 1){
                        this.customerList[i].name = '公海客户';
                      } 
                      if(this.customerList[i].name == null){
                        this.customerList[i].name = '公海客户';
                      }
                }
              this.pagingData.total = result.data.total;
              this.pagingData.pageNum = result.data.pageNum > 0 ? result.data.pageNum : 1;
            }else if(result.data = null) {
              this.pagingData.total = 0;
              this.pagingData.pageNum = 0;
            } else {
              this.customerList = [];
              this.pagingData.total = 0;
              this.pagingData.pageNum = 0;
            }
          })
      },
      handleCurrentChange(val) {
          this.filter.pageNum = val;
          this.customerListCurrentPage = val;
          this.matchCustomers();
      },
      handleSizeChange(val) {
          this.filter.pageSize = val;
          this.filter.pageNum = 1;
          this.matchCustomers();
      },
      goSeas(name){
        this.$router.push({path: '/customer/seas?customerName=' + name});
      },
      goSeasDetail(data){
        this.$router.push({path: '/customer/detail?id=' + data.id + '&customerContactId=' + data.customerContactId});
      },
      getUserData() {
          this.$store.dispatch('getUserPersonalData')
            .then((response) => {
              if(!response){return}
              var result = response.data;
              if (result.code === 0) {
                  if(result.data ) {
                      this.$store.commit(USER_DATA , {userData : result.data});
                      setToken('userData',JSON.stringify(result.data));
                      this.addCustomerForm.userId = result.data.id;
                      this.userName = result.data.name;
                  }
              }
          })
      },
      getIndustry(val) {
          this.addCustomerForm.customerIndustry = val;
      }
    },
    
    created () {
        if (process.BROWSER_BUILD ) {
            const loggedUser = window.localStorage.getItem('token');
            if(loggedUser){
                this.$store.commit(BG_LOGIN,{ bgLogin: false});
                this.getCustomerLevels();     //获取客户分类
                this.$store.dispatch('getAllProvinceList');   //获取省市区信息
                this.getUserData();           //获取用户信息
                /*
                  行业已写在配置js文件
                */
                //this.$store.dispatch('getIndustryList',{code: -1});   //获取行业信息
                var phone = this.$route.query.phone;
                if(phone ) {
                    this.addCustomerForm.tel = phone;
                }
            }else {
                this.$store.commit(BG_LOGIN,{ bgLogin: true});
                window.open (
                    '/login?from=tel',
                    'newwindow',
                    'height=400,width=600,top=50%,left=50%,toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no'
                )
            }
            if(this.pageTabsList[this.pageTabsList.length-1].name == 'CRM') {
                let arr = this.pageTabsList;
                arr[arr.length-1].name = this.tabName;
                this.$store.commit('PAGETABSLIST',{data:arr})
            }
        }
    },
    mounted(){
        if(this.addCustomerForm.customerName){
          this.matchCustomers()
          if(this.addCustomerForm.areaId){
            this.addrValue = [this.addCustomerForm.provinceId, this.addCustomerForm.cityId, this.addCustomerForm.areaId];
          }else{
            this.addrValue = [];
          }
          
          if(this.addCustomerForm.customerIndustry){
            let list = this.addCustomerForm.customerIndustry;
            this.industryValue[0] = list[0];
            this.industryValue[1] = this.industryValue[0]+list[1]+list[2];
            this.industryValue[2] = this.industryValue[1]+list[3];
            this.industryValue[3] = this.industryValue[2]+list[4];
          }else{
            this.industryValue = [];
          }
        }else{
          this.$store.commit('INIT_ADD_CUSTOMER_FORM',{data:""});
        }
    }
  }

</script>

<style scoped lang="scss">
  .action_row {
    width: 100%;
    float: left;
    margin-top: 40px;
    .top_close{
    float: left;
    margin-left: 40px;
    }
    .top_save {
      float: right;
      margin-right: 40px;
    }
  }
  .action_row_exit {
    text-align: center;
  }

  h4 {
    color: #008dd8;
  }

  .form-input {
    margin-right: 10%;
  }
  .seas {
    cursor: pointer;
    color: rgb(20,136,255);
  }
  .bg-login {
    position: fixed;
    top:0;
    left: 0;
    right: 0;
    bottom:0;
    background: rgba(0,0,0,0.5);
    z-index: 999;
  }
  #addbox{
  	.el-table{
			.cell{
				padding-left: 0px !important;
			}
  	}
  }
</style>